/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function (s) {
    if (s && s.length <= 1) return s

    let sLen = s.length,
        dp = new Array(sLen + 1).fill(0).map(() => new Array(sLen + 1).fill(0)),
        max = 0,
        startIndex = 0;

    for (let i = sLen; i > 0; i--) {
        for (let j = i; j <= sLen; j++) {
            if (s[i - 1] === s[j - 1]) {
                if (i === j) {
                    dp[i][j] = 1
                } else if (j - i === 1) {
                    dp[i][j] = 2
                } else if (dp[i + 1][j - 1] != 0) {
                    dp[i][j] = dp[i + 1][j - 1] + 2
                }
                if (dp[i][j] > max) {
                    max = dp[i][j]
                    startIndex = i - 1
                }
            }
        }
    }
    return max === 0 ? s[0] : s.slice(startIndex, max + startIndex)
};

/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function(s) {
    if (s && s.length <= 1) return s

    let length = 0, res = ''
    for (let i = 0; i < s.length; i++) {
        length = Math.max(getExpendStr(s, i, i), getExpendStr(s, i, i + 1))
        res = res.length > length ? res : s.substr(i - Math.floor((length - 1) / 2), length)
    }
    return res
};

function getExpendStr(s, l, r) {
    while (l >= 0 && r < s.length && s.charAt(l) === s.charAt(r)) {
        l--
        r++
    }
    return r - l - 1
}